package com.xixi.aop;

import com.xixi.anno.Log;
import com.xixi.entity.OperationLog;
import com.xixi.service.OperaterService;
import com.xixi.utils.CurrentUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;

@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperaterService operaterService;

    @Around("@annotation(com.xixi.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行目标方法
        long startTime = System.currentTimeMillis();
        // 执行目标方法
        Object result = joinPoint.proceed();
        // 计算耗时
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;
        // 创建并填充日志对象
        OperationLog log = new OperationLog();

        // 设置操作用户信息
        Integer currentUserId = CurrentUser.getCurrentId();
        String currentUserName = CurrentUser.getCurrentName();
        String currentUserRole = CurrentUser.getCurrentRole();
        log.setOperatorId(currentUserId);
        log.setOperatorName(currentUserName);
        log.setOperatorType(currentUserRole);
        // 设置操作类型（根据方法名简单判断）
        String methodName = joinPoint.getSignature().getName();
        if (methodName.contains("buy") || methodName.contains("purchase")) {
            log.setOperationType("BUY");
        } else if (methodName.contains("insert") || methodName.contains("create")) {
            log.setOperationType("ADD");
        } else if (methodName.contains("update") || methodName.contains("modify")) {
            log.setOperationType("UPDATE");
        } else if (methodName.contains("delete") || methodName.contains("remove")) {
            log.setOperationType("DELETE");
        } else if (methodName.contains("pay")) {
            log.setOperationType("PAY");
        } else if (methodName.contains("refund")) {
            log.setOperationType("REFUND");
        } else if (methodName.contains("cancel")) {
            log.setOperationType("CANCEL");
        } else if (methodName.contains("receive")) {
            log.setOperationType("RECEIVE");
        } else if (methodName.contains("publish")) {
            log.setOperationType("PUBLISH");
        }


        // 设置目标类型（根据类名简单判断）
        String className = joinPoint.getTarget().getClass().getSimpleName();
        if (className.contains("Product")) {
            log.setTargetType("PRODUCT");
        } else if (className.contains("Order")) {
            log.setTargetType("ORDER");
        } else if (className.contains("User")) {
            log.setTargetType("USER");
        }

        // 设置时间
        log.setCostTime(costTime);
        log.setOperationTime(LocalDateTime.now());

        // 保存日志
        operaterService.insert(log);

        return result;
    }
}